package com.ktjiaoyu;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest
@RunWith(SpringRunner.class)
public class ShiroTester {
    @Test
    public void test(){
        //1.创建Realm 数据源
        IniRealm realm=new IniRealm("classpath:shiro.ini");
        //2.创建安全员
        DefaultSecurityManager securityManager=new DefaultSecurityManager();
        securityManager.setRealm(realm);
        //3.把安全员绑定
        SecurityUtils.setSecurityManager(securityManager);
        //4.获取subject
        Subject subject = SecurityUtils.getSubject();
        //5.登录
        UsernamePasswordToken token=new UsernamePasswordToken("laotou","888888");
        try {
            subject.login(token);
            System.out.println(subject.isAuthenticated());
            System.out.println(subject.getPrincipal());

            //硬编码授权

            //判断是否拥有某一个角色（身份）
            if(subject.hasRole("管理员")){
                System.out.println("拥有管理员的角色");
            }else {
                System.out.println("没有管理员的角色");
            }

            if(subject.hasRole("客户经理")){
                System.out.println("拥有客户经理的角色");
            }else {
                System.out.println("没有客户经理的角色");
            }

            //判断是否拥有某一个权限(权利)
            if(subject.isPermitted("user:list")){
                System.out.println("拥有查看用户列表权限");
            }else{
                System.out.println("没有查看用户列表权限");
            }

            try {
                subject.checkPermission("user:list");
                System.out.println("拥有查看用户列表权限");
            } catch (AuthorizationException e) {
                e.printStackTrace();
                System.out.println("没有查看用户列表权限");
            }
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
    }
}
